// createRouter 用于创建路由得函数
// createWebHashHistory 用于创建哈希路由得函数
import { createRouter, createWebHashHistory } from 'vue-router'

import Layout from '@/views/Layout'
import Home from '@/views/home/index'
import TopCategory from '@/views/category/index'
import SubCategory from '@/views/category/sub'
import Login from '@/views/login/index'
import LoginCallback from '@/views/login/callback'
import store from '@/store'
import Checkout from '@/views/member/pay/checkout.vue'
const Goods = () => import('@/views/goods/index')
const Cart = () => import('@/views/cart/index')

// 配置路由映射关系，路径和组件
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '', component: Home },
      { path: '/category/:id', component: TopCategory },
      { path: '/category/sub/:id', component: SubCategory },
      { path: '/product/:id', component: Goods },
      { path: '/cart', component: Cart },
      { path: 'member/checkout', component: Checkout }
    ]
  },
  { path: '/login', component: Login },
  { path: '/login/callback', component: LoginCallback }
]

// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 路由进阶 - 滚动行为
  scrollBehavior (to, from, savedPosition) {
    if (to.path !== '/') {
      // 始终滚到顶部
      return { top: 0, behavior: 'smooth' }
      // Vue2返回的是 { x:0 , y:0 }
      // Vue3返回的是 { left:0 , top:0 }
    } else {
      return savedPosition
    }
  }

})
// 路由前置导航守卫
router.beforeEach((to, from) => {
  // 跳转去member开头的地址，却没有登录
  if (to.path.startsWith('/member') && !store.state.user.profile.token) {
    // 跳转到登录页，并传递
  //   next('/login?redirectUrl=' + to.fullPath)
  // } else {
  //   next()
  // }
    return { path: '/login', query: { redirectUrl: to.fullPath } }
  }
})

// 导出路由实例
export default router
